'use client';

import { useCallback, useEffect, useState } from 'react';
import classNames from 'classnames';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function ColorModeItem(
  this: any,
  {
    name,
    isShowDropdownToggle = false,
    aPy0 = false,
    callback,
    ulClass,
    translatedFields,
  }: {
    name?: string;
    isShowDropdownToggle?: boolean;
    aPy0?: boolean;
    callback?: (theme: 'auto' | 'dark' | 'light') => void;
    ulClass?: string;
    translatedFields: PrefixedTTranslatedFields<'navbar'>;
  },
) {
  const [colorMode, setColorMode] = useState('auto');

  const getStoredTheme = useCallback(() => {
    return localStorage.getItem('theme');
  }, []);

  const setStoredTheme = useCallback((theme: string) => {
    localStorage.setItem('theme', theme);
  }, []);

  const getPreferredTheme = useCallback(() => {
    const storedTheme = getStoredTheme();
    if (storedTheme) {
      return storedTheme;
    }

    return matchMedia('(prefers-color-scheme: dark)').matches
      ? 'dark'
      : 'light';
  }, [getStoredTheme]);

  const setTheme = useCallback((theme: string) => {
    const qName = 'data-bs-theme';
    if (
      theme === 'auto' &&
      matchMedia('(prefers-color-scheme: dark)').matches
    ) {
      document.documentElement.setAttribute(qName, 'dark');
    } else {
      document.documentElement.setAttribute(qName, theme);
    }
    setColorMode(theme);
    if (typeof callback === 'function') {
      callback(theme as 'auto' | 'dark' | 'light');
    }
  }, []);

  const onClickColorMode = useCallback(
    (theme?: string) => {
      const preferredTheme = theme ? theme : getPreferredTheme();
      setStoredTheme(preferredTheme);
      setTheme(preferredTheme);
    },
    [getPreferredTheme, setStoredTheme, setTheme],
  );

  useEffect(() => {
    function handleChange() {
      const storedTheme = getStoredTheme();
      if (storedTheme !== 'light' && storedTheme !== 'dark') {
        setTheme(getPreferredTheme());
      }
    }

    if (typeof localStorage !== 'undefined') {
      onClickColorMode();
      matchMedia('(prefers-color-scheme: dark)').addEventListener(
        'change',
        handleChange,
      );
    }

    return () => {
      matchMedia('(prefers-color-scheme: dark)').removeEventListener(
        'change',
        handleChange,
      );
    };
  }, [getPreferredTheme, getStoredTheme, onClickColorMode, setTheme]);

  return (
    <ul className={classNames('navbar-nav', ulClass)}>
      <li className="nav-item dropstart">
        <a
          className={classNames('nav-link', {
            'dropdown-toggle': isShowDropdownToggle,
            'py-0': aPy0,
          })}
          role="button"
          data-bs-toggle="dropdown"
          aria-expanded="false"
        >
          {colorMode === 'light' &&
            (name ? name : <i className="bi bi-brightness-high-fill"></i>)}
          {colorMode === 'dark' &&
            (name ? name : <i className="bi bi-moon-stars-fill"></i>)}
          {colorMode === 'auto' &&
            (name ? name : <i className="bi bi-circle-half"></i>)}
        </a>
        <ul
          className="dropdown-menu text-center"
          style={{
            ['--bs-dropdown-min-width' as string]: '8rem',
          }}
        >
          <button
            onClick={onClickColorMode.bind(this, 'light')}
            type="button"
            className={classNames('dropdown-item d-flex align-items-center', {
              active: colorMode === 'light',
            })}
          >
            <i className="bi bi-brightness-high-fill me-2"></i>
            {translatedFields.light}
            {colorMode === 'light' && <i className="bi bi-check2 ms-2"></i>}
          </button>

          <button
            onClick={onClickColorMode.bind(this, 'dark')}
            type="button"
            className={classNames('dropdown-item d-flex align-items-center', {
              active: colorMode === 'dark',
            })}
          >
            <i className="bi bi-moon-stars-fill me-2"></i>
            {translatedFields.dark}
            {colorMode === 'dark' && <i className="bi bi-check2 ms-2"></i>}
          </button>

          <button
            onClick={onClickColorMode.bind(this, 'auto')}
            type="button"
            className={classNames('dropdown-item d-flex align-items-center', {
              active: colorMode === 'auto',
            })}
          >
            <i className="bi bi-circle-half me-2"></i>
            {translatedFields.auto}
            {colorMode === 'auto' && <i className="bi bi-check2 ms-2"></i>}
          </button>
        </ul>
      </li>
    </ul>
  );
}
